package com.demo.onvif.service.impl;

import com.demo.onvif.domain.OnvifChannelEntity;
import com.demo.onvif.domain.OnvifEntity;
import com.demo.onvif.service.IOnvifService;
import com.demo.onvif.utils.ONVIFDeviceDiscoveryFIN;
import de.onvif.soap.OnvifDevice;
import lombok.extern.slf4j.Slf4j;
import org.onvif.ver10.schema.Profile;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Service
@Slf4j
public class OnvifServiceImpl implements IOnvifService {

    @Override
    public List<OnvifEntity> discoverOnvif(String ip) throws IOException {
        return ONVIFDeviceDiscoveryFIN.discoverOnvif(ip);
    }

    @Override
    public Set<OnvifChannelEntity> getOnvifChannel(OnvifDevice onvifDevice) {
        onvifDevice.getSoap().setLogging(Boolean.FALSE);
        //数据源
        List<Profile> profiles = onvifDevice.getDevices().getProfiles();
        //返回值
        Set<OnvifChannelEntity> onvifChannelEntityList = new HashSet<>();

        for (Profile profile : profiles) {
            OnvifChannelEntity item = new OnvifChannelEntity();
            int channel = getChannel(profile);
            if (channel != -1) {
                item.setIndex(channel);
            }else {
                continue;
            }
            onvifChannelEntityList.add(item);
        }
        return onvifChannelEntityList;
    }

    private static String getSourceToken(Profile profile) {
        if (profile.getVideoSourceConfiguration() != null) {
            return profile.getVideoSourceConfiguration().getSourceToken();
        } else if (profile.getAudioSourceConfiguration() != null) {
            return profile.getAudioSourceConfiguration().getSourceToken();
        } else {
            return "";
        }
    }

    public static int getChannel(Profile profile) {
        String token = profile.getToken();
        String source = getSourceToken(profile);
        log.info("onvif profile: {}, source: {}", token, source);

        if (source.isEmpty()) {
            return -1;
        }

        // 大华/宇视source token: 00100
        if (source.length() == 5) {
            if (!"00".equals(source.substring(3))) {
                return -1;
            }

            int chn = Integer.parseInt(source.substring(0, 3));
            if (token.startsWith("token:")) {
                return chn;
            }
            if (token.startsWith("MediaProfile")) {
                return chn + 1;
            }
            return -1;
        }

        // 获取source token末尾所有数字
        Pattern pattern = Pattern.compile("\\d+$");
        Matcher matcher = pattern.matcher(source);
        if (matcher.find()) {
            return Integer.parseInt(matcher.group());
        }
        return 1;
    }
}
